# -*- coding: utf-8 -*-
#sample.py

import datetime
import zope.interface
import pytz

from dbformlib.dbformlib import DBFormlibContent
from interfaces import IDBTestContent

class DBTestContent(DBFormlibContent):
    zope.interface.implements(IDBTestContent)

    def _get_form_data(self, crud_id, in_params={}):
        if crud_id == 'edit' or crud_id=='delete' or crud_id=='custom'\
          or crud_id=='view':
            return {'name':'Mercedes',
                'tnow':datetime.datetime(2007, 01, 01, 00,
                                            00, 00, 00, tzinfo=pytz.UTC)}
        elif crud_id == 'add':
            # you may enter some default values here
            return {'name':'new name'}
  
    def _set_form_data(self, crud_id, data, errors=[]):
        # Save data to RDBMS here and handle errors
        # Error message should be appended to errors list like:
        # errors.append(u'DBError message')
        
        # simulate DB error when max_size == 20
        # beware that max_size may not exist in 'data'
        # when this field is omited on form!
        if data.get('max_size', 0)==20:
            errors.append(u'Error while executing insert '
                          +'xyz into xyz statement!')
        if crud_id=='add':
            # sql that adds new row into db may return 
            # new row id, we're simulating this:
            return 23
        elif crud_id=='edit':
            pass # sql statements for updating data
        elif crud_id=='delete':
            # simulate error if row_id==2
            if data.get('row_id', 0)=='2':
                errors.append(u'Error while executing insert '
                          +'xyz into xyz statement!')            
        else:
            pass # sql statements for inserting data
        return None
  
    def nextURL(self, crud_id=''):
        """ This might be used by add and delete forms to redirect
            somewhere after adding or deleting row
        """
        if crud_id=='add':
            data = self.get_data()
            return '@@edit.html?row_id=%s' % (data['row_id'])
        return '@@add.html'